package com.shujia.spark

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

object Demo11Join {
  def main(args: Array[String]): Unit = {
    val conf: SparkConf = new SparkConf()
      .setMaster("local")
      .setAppName("map")


    val sc = new SparkContext(conf)

    val nameRDD: RDD[(String, String)] = sc.parallelize(List(("001", "张三"), ("002", "李四"), ("003", "王五"), ("004", "小伟")))

    val ageRDD: RDD[(String, Int)] = sc.parallelize(List(("001", 23), ("002", 24), ("003", 25)))

    /**
      * join: 默认是inner join 。 两个rdd都必须是kv格式
      *
      */

    val joinRDD: RDD[(String, (String, Int))] = nameRDD.join(ageRDD)


    //join之后整理数据
    val rdd3: RDD[(String, String, Int)] = joinRDD.map(kv => {
      val id: String = kv._1
      val name: String = kv._2._1
      val age: Int = kv._2._2
      (id, name, age)
    })


    //如果rdd结构比较复杂，可以通过case 简写，提高可读性
    val rdd4: RDD[(String, String, Int)] = joinRDD.map {
      //一行一行对rdd的数据进行匹配（匹配类型）
      case (id: String, (name: String, age: Int)) => {
        (id, name, age)
      }
    }

    // rdd4.foreach(println)


    val leftJoinRDD: RDD[(String, (String, Option[Int]))] = nameRDD.leftOuterJoin(ageRDD)


    val rdd5: RDD[(String, String, Int)] = leftJoinRDD.map(kv => {
      val id: String = kv._1
      val name: String = kv._2._1

      val age: Int = kv._2._2.getOrElse(0)

      (id, name, age)
    })


    val rdd6: RDD[(String, String, Int)] = leftJoinRDD.map {
      //匹配关联成功的情况
      case (id: String, (name: String, Some(age))) => {
        (id, name, age)
      }
      //匹配没有关联上的情况
      case (id: String, (name: String, None)) => {
        (id, name, 0)
      }
    }

    rdd6.foreach(println)

  }

}
